<?php

namespace app\api\controller;

use app\BaseController;
use think\facade\View;
use think\facade\Config;
use think\facade\Request;
// use think\facade\Session;
use app\common\model\SystemAdmin;
use app\common\model\Store;
use app\common\model\User;
use app\common\model\Product;
use app\common\model\ProductType;
use app\common\model\ProductBanner;
use app\common\model\FileLog;
use app\common\controller\Handle;
use GatewayWorker\Lib\Gateway;
use think\Exception;
use think\facade\Db;

class ApiProject extends ApiBase
{
    public function initialize()
    {
        parent::initialize();
        $this->Product = new Product;
        $this->Store = new Store;
        $this->ProductType = new ProductType;
        $this->ProductBanner = new ProductBanner;
        $this->FileLog = new FileLog;
    }


    // 保存添加修改的类型
    public function addType()
    {
        // 判断店铺是否正常
        $is_store = $this->storeIsNormal($this->uid);

        if($is_store['code'] == 1){
            return json(['status' => 0, 'msg' =>$is_store['msg']]);
        }

        $store_id = $is_store['store_id'];

        $data = request()->post();

     
        if(empty($data['arr'])){
            return json(['status' => 0, 'msg' =>"请上次相关参数"]);
        }

        foreach($data['arr'] as $key=>$val){
            $add= [];
            $update = [];
            if(!empty($val['id'])){
                $this->ProductType->where(['id'=>$val['id']])->update(['name'=>$val['name'],'parent_id'=>0,'sort'=>$key+1,"store_id"=>$store_id,"update_at"=>date("Y-m-d H:i:s")]);
                $parent_id =$val['id'];
            }else{
                $addParent = [
                    'parent_id'=>0,
                    'name'=>$val['name'],
                    'created_at'=>date("Y-m-d H:i:s"),
                    'update_at'=>date("Y-m-d H:i:s"),
                    'store_id'=>$store_id,
                    'sort'=>$key+1,
                ];

                $type = $this->ProductType->create($addParent);
                $parent_id =$type->id;
            }


            if(!empty($val['child'])){
                foreach($val['child'] as $k=>$v){
                  
                    if(empty($v['id'])){
                        $add[] =[
                            'parent_id'=>$parent_id,
                            'name'=>$v['name'],
                            'created_at'=>date("Y-m-d H:i:s"),
                            'update_at'=>date("Y-m-d H:i:s"),
                            'store_id'=>$store_id,
                            'sort'=>$k+1,
                        ]; 
                    }else{

                        $update= [
                            'parent_id'=>$parent_id,
                            'name'=>$v['name'],
                            'created_at'=>date("Y-m-d H:i:s"),
                            'update_at'=>date("Y-m-d H:i:s"),
                            'store_id'=>$store_id,
                            'sort'=>$k+1,
                        ];

                        $result = $this->ProductType->where(['id'=>$v['id']])->update($update);
                    }
                   
                }

                if(!empty($add)){
                    $res = $this->ProductType->insertAll($add);
                }

            }
        }

        return json(['status' => 1, 'msg' => '保存成功']);
    }

    // 查询分类
    public function getType()
    {
          // 判断店铺是否正常
        $is_store = $this->storeIsNormal($this->uid);
        $data = [];
        if($is_store['code'] == 1){
            $data = [
                0=>[
                    "name"=>"宝宝宴",
                    "parent_id"=>0,
                    "sort"=>1,
                    "child"=>[
                        0=>[
                            "name"=>"男宝宝宴",
                            "sort"=>1,
                        ],
                        1=>[
                            "name"=>"女宝宝宴",
                            "sort"=>2,
                        ]
                    ]
                ],
                1=>[
                    "name"=>"企业布置",
                    "parent_id"=>0,
                    "sort"=>2,
                    "child"=>[
                        0=>[
                            "name"=>"商业美陈",
                            "sort"=>1,
                        ],
                        1=>[
                            "name"=>"企业年会",
                            "sort"=>2,
                        ],
                        2=>[
                            "name"=>"开业庆典",
                            "sort"=>3,
                        ]
                    ]
                ],
                2=>[
                    "name"=>"寿宴",
                    "parent_id"=>0,
                    "sort"=>3,
                    
                ],
                3=>[
                    "name"=>"婚房",
                    "parent_id"=>0,
                    "sort"=>4,
                    
                ],
                4=>[
                    "name"=>"求婚告白",
                    "parent_id"=>0,
                    "sort"=>5,
                ],
                5=>[
                    "name"=>"毕业季",
                    "parent_id"=>0,
                    "sort"=>6,
                ],
                6=>[
                    "name"=>"订婚宴",
                    "parent_id"=>0,
                    "sort"=>7,
                ]
            ];

            return json(['status' => 1, 'data' => $data]);
                    
        }else{
            $store_id = $is_store['store_id'];
            $typeList = $this->ProductType->where(['store_id'=>$store_id,"deleted_at"=>null])->order('sort asc')->order('id',"asc")->field("id,name,sort,parent_id,store_id")->select()->toArray();

            if(!empty($typeList)){
                $data = list_to_tree($typeList);
            }else{
                $data = [];
            }
            return json(['status' => 1, 'data' => $data]);
        
        }

    }

    // 删除分类
    public function delType()
    {
        // 判断店铺是否正常
        $is_store = $this->storeIsNormal($this->uid);
        if($is_store['code'] == 1){
            return json(['status' => 0, 'msg' =>$is_store['msg']]);
        }

        $store_id = $is_store['store_id'];

        $data = request()->post();
      

        if(empty($data['id'])){
            return json(['status' => 0, 'msg' =>"请上传分类ID"]);
        }

        $list = $this->ProductType->getOne(['id' =>$data['id']], 'id,name,parent_id,store_id,sort');

        if(empty($list)){
            return json(['status' => 0, 'msg' =>"类型不存在"]);
        }

        if($list['parent_id'] == 0){
            // 查询下面是否有子类
            $childList = $this->ProductType->getOne(['parent_id' =>$data['id'],'deleted_at'=>null], 'id,name,parent_id,store_id,sort');

            if(!empty($childList)){
                return json(['status' => 0, 'msg' =>"请先删除一级分类，下面的子类"]);
            }

            // 判断下面是否有商品
            $storeList = $this->Product->getOne(['type_id' =>$data['id']], 'id,name');

            if(!empty($storeList)){
                return json(['status' => 0, 'msg' =>"请先删除分类下面商品"]);
            }

            $res = $this->ProductType->where(['id'=>$data['id']])->update(["deleted_at"=>date("Y-m-d H:i:s")]);
        }else{
            $storeList = $this->Product->getOne(['type_child_id' =>$data['id'],'deleted_at'=>null], 'id,name');

            if(!empty($storeList)){
                return json(['status' => 0, 'msg' =>"请先删除分类下面商品"]);
            }

            $res = $this->ProductType->where(['id'=>$data['id']])->update(["deleted_at"=>date("Y-m-d H:i:s")]);
        }

        return json(['status' => 1,'msg' => '删除成功' ]);
    }

    // 添加商品
    public function  addProject()
    {
        // 判断店铺是否正常
        $is_store = $this->storeIsNormal($this->uid);

        if($is_store['code'] == 1){
            return json(['status' => 0, 'msg' =>$is_store['msg']]);
        }
 
        $store_id = $is_store['store_id'];

        $data = request()->post();

        if(empty($data['name'])){
            return json(['status' => 0, 'msg' =>"请上传商品主题"]);
        }

        if(empty($data['type_id'])){
            return json(['status' => 0, 'msg' =>"请选择商品类型"]);
        }

        if(empty($data['logo'])){
            return json(['status' => 0, 'msg' =>"请选择商品封面"]);
        }

        if(empty($data['price'])){
            return json(['status' => 0, 'msg' =>"请上传商品售价"]);
        }

        if(empty($data['content'])){
            return json(['status' => 0, 'msg' =>"请上传内容"]);
        }

        if(empty($data['bargain_set'])){
            return json(['status' => 0, 'msg' =>"请选择是否开启砍一刀"]);
        }

        if(empty($data['video_or_banner'])){
            return json(['status' => 0, 'msg' =>"请选择上传展示商品轮播图还是小视频"]);
        }

        $add = [
            "name"=>$data['name'],
            "type_id"=>$data['type_id'],
            "logo"=>$data['logo'],
            "price"=>$data['price'],
            "content"=>$data['content'],
            "bargain_set"=>$data['bargain_set'],
            "video_or_banner"=>$data['video_or_banner'],
            "store_id"=>$store_id,
            "created_at"=>date("Y-m-d H:i:s"),
            "update_at"=>date("Y-m-d H:i:s"),
        ];

        if($data['bargain_set'] == 1){
            if(empty($data['bargain_people'])){
                return json(['status' => 0, 'msg' =>"请上传可以砍单人数"]);
            }

            if(empty($data['bargain_price'])){
                return json(['status' => 0, 'msg' =>"请上传一共可以砍多少钱"]);
            }

            $add['bargain_people'] = $data['bargain_people'];
            $add['bargain_price'] = $data['bargain_price'];
        }

        if($data['video_or_banner'] == 1){
            if(empty($data['video_url'])){
                return json(['status' => 0, 'msg' =>"请上传视频路径"]);
            }
            $add['video_url'] = $data['video_url'];
        }else{
            if(empty($data['banner_list'])){
                return json(['status' => 0, 'msg' =>"请上传轮播图片路径"]);
            }
        }
        
        if(!empty($data['type_child_id'])){
            $add['type_child_id'] = $data['type_child_id'];
        }

        if(!empty($data['virtual_number'])){
            $add['virtual_number'] = $data['virtual_number'];
            $add['sum_number'] = $data['virtual_number'];
        }

        if(!empty($data['sort'])){
            $add['sort'] = $data['sort'];
        }

        if(!empty($data['status'])){
            $add['status'] = $data['status'];
        }

        // 开启事务
        Db::startTrans();
        try {

            $res = $this->Product->create($add);
            $product_id = $res->id;
            $addBanner = [];
            if($data['video_or_banner'] == 2){
                foreach($data['banner_list'] as $k=>$v){
                    $addBanner[] = [
                        "product_id"=>$product_id,
                        "file_url"=>$v,
                        "sort"=>$k+1,
                        "created_at"=>date("Y-m-d H:i:s"),
                        "update_at"=>date("Y-m-d H:i:s"),
                        "deleted_at"=>date("Y-m-d H:i:s"),
                    ];
                }

                $resBanner = $this->ProductBanner->insertAll($addBanner);
            }

            // 提交事务
            Db::commit();
            return json(['status' => 1, 'msg' => '操作成功']);
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['status' => 0, 'msg' =>$e->getMessage()]);
        }
    }


    // 商品类型Api
    public function apiType()
    {
        $is_store = $this->storeIsNormal($this->uid);

        if($is_store['code'] == 1){
            return json(['status' => 0, 'msg' =>$is_store['msg']]);
        }

        if(empty($data['parent_id'])){
            $data['parent_id'] = 0;
        }
        $store_id = $is_store['store_id'];

        $typeList = $this->ProductType->where(['store_id'=>$store_id,"deleted_at"=>null,"parent_id"=>$data['parent_id']])->order('sort',"asc")->field("id,name,sort,parent_id,store_id")->select()->toArray();

        return json(['status' => 1, 'data' => $typeList]);

    }

    // 商品列表
    public function listProject()
    {

        // 存储空间对应的域名
        $domain = config('sysconfig.qiniu_domain');


        // 判断店铺是否正常
        $is_store = $this->storeIsNormal($this->uid);

        if($is_store['code'] == 1){
            return json(['status' => 0, 'msg' =>$is_store['msg']]);
        }

        $store_id = $is_store['store_id'];

        $where['store_id'] = $store_id;
        $where['deleted_at'] = null;

        if(!empty($data['type_id'])){
            $where['type_id'] = $data['type_id'];
        }

        if(!empty($data['type_child_id'])){
            $where['type_child_id'] = $data['type_child_id'];
        }

        if(!empty($data['status'])){
            $where['status'] = $data['status'];
        }

        
        if(empty($data['limit'])){
            $data['limit'] = 10;
        }

        if(empty($data['page'])){
            $data['page'] = 1;
        }

        $list = $this->Product->getPagelist($where,"id,name,sort,logo,price,store_id,sum_number,type_id,status",'sort asc');

        foreach($list as $key=>$val){
            // $val->logo = $domain."/".$val['logo'];
            $val->type_name = $this->ProductType->where(['id'=>$val['type_id']])->value("name");
            
            
        }

        $count = $this->Product->countRows($where);

        $pages = ceil($count/$data['limit']);

        return json(['status'=> 1,'data'=>$list,'pages'=>$pages,"count"=>$count]);
    }

    public function projectAll()
    {

        // 存储空间对应的域名
        $domain = config('sysconfig.qiniu_domain');


        // 判断店铺是否正常
        $is_store = $this->storeIsNormal($this->uid);

        if($is_store['code'] == 1){
            return json(['status' => 0, 'msg' =>$is_store['msg']]);
        }

        $store_id = $is_store['store_id'];

        $where['store_id'] = $store_id;
        $where['deleted_at'] = null;

        // if(!empty($data['type_id'])){
        //     $where['type_id'] = $data['type_id'];
        // }

        // if(!empty($data['type_child_id'])){
        //     $where['type_child_id'] = $data['type_child_id'];
        // }

        
        // if(empty($data['limit'])){
        //     $data['limit'] = 10;
        // }

        // if(empty($data['page'])){
        //     $data['page'] = 1;
        // }

        $list = $this->Product->getAllOrder($where,"id,name,logo,content",'sort asc');

        foreach($list as $key=>$val){
            // $val->hostlogo = $domain."/".$val['logo'];
            // $val->logo = $domain."/".$val['logo'];
        //     // $val->type_name = $this->ProductType->where(['id'=>$val['type_id']])->value("name");
            
            
        }

        // $count = $this->Product->countRows($where);
// 
        // $pages = ceil($count/$data['limit']);

        return json(['status'=> 1,'data'=>$list]);
    }

    // 商品详情
    public function getProject()
    {
        // 存储空间对应的域名
        $domain = config('sysconfig.qiniu_domain');

        // 判断店铺是否正常
        $is_store = $this->storeIsNormal($this->uid);

        if($is_store['code'] == 1){
            return json(['status' => 0, 'msg' =>$is_store['msg']]);
        }
 
        $store_id = $is_store['store_id'];

        $data = request()->post();

        if(empty($data['id'])){
            return json(['status' => 0, 'msg' =>"请上传产品ID"]);
        }

        $list = $this->Product->getOne(['id' =>$data['id'],'deleted_at'=>null]);

        if(empty($list)){
            return json(['status' => 0, 'msg' =>"商品不存在"]);
        }


        $list['content'] = str_replace("api_project",$domain."/api_project",$list['content']);

        if(empty($list)){
            return json(['status' => 0, 'msg' =>"请产品不存在"]);
        }

        // $list['logo'] = $domain."/".$list['logo'];

        $list['type_name'] = $this->ProductType->where(['id'=>$list['type_id']])->value("name");

        if(!empty($list['type_child_id'])){
            $list['type_child_name'] = $this->ProductType->where(['id'=>$list['type_child_id']])->value("name");
        }else{
            $list['type_child_name'] = "";
        }

        if($list['video_or_banner'] == 2){
            $list['banner_list'] = $this->ProductBanner->where(["product_id"=>$data['id']])->field("id,file_url")->select();

            if(!empty($list['banner_list'])){
                foreach($list['banner_list'] as $key=>$val){
                    $val->file_url = $domain."/".$val['file_url'];
                }
            }
        }

        
        return json(['status'=> 1,'data'=>$list]);


    }

    // 修改商品
    public function  updateProject()
    {
        // 判断店铺是否正常
        $is_store = $this->storeIsNormal($this->uid);

        if($is_store['code'] == 1){
            return json(['status' => 0, 'msg' =>$is_store['msg']]);
        }

        $store_id = $is_store['store_id'];

        $data = request()->post();


        if(empty($data['id'])){
            return json(['status' => 0, 'msg' =>"请上传产品ID"]);
        }

        $list = $this->Product->getOne(['id' =>$data['id'],'deleted_at'=>null]);

        if(empty($list)){
            return json(['status' => 0, 'msg' =>"请产品不存在"]);
        }



        if(empty($data['name'])){
            return json(['status' => 0, 'msg' =>"请上传商品主题"]);
        }

        if(empty($data['type_id'])){
            return json(['status' => 0, 'msg' =>"请选择商品类型"]);
        }

        if(empty($data['logo'])){
            return json(['status' => 0, 'msg' =>"请选择商品封面"]);
        }

        if(empty($data['price'])){
            return json(['status' => 0, 'msg' =>"请上传商品售价"]);
        }

        if(empty($data['content'])){
            return json(['status' => 0, 'msg' =>"请上传内容"]);
        }

        if(empty($data['bargain_set'])){
            return json(['status' => 0, 'msg' =>"请选择是否开启砍一刀"]);
        }

        if(empty($data['video_or_banner'])){
            return json(['status' => 0, 'msg' =>"请选择上传展示商品轮播图还是小视频"]);
        }

        $save = [
            "name"=>$data['name'],
            "type_id"=>$data['type_id'],
            "logo"=>$data['logo'],
            "price"=>$data['price'],
            "content"=>$data['content'],
            "bargain_set"=>$data['bargain_set'],
            "video_or_banner"=>$data['video_or_banner'],
            "store_id"=>$store_id,
            "update_at"=>date("Y-m-d H:i:s"),
        ];

        if($data['bargain_set'] == 1){
            if(empty($data['bargain_people'])){
                return json(['status' => 0, 'msg' =>"请上传可以砍单人数"]);
            }

            if(empty($data['bargain_price'])){
                return json(['status' => 0, 'msg' =>"请上传一共可以砍多少钱"]);
            }

            $save['bargain_people'] = $data['bargain_people'];
            $save['bargain_price'] = $data['bargain_price'];
        }

        if($data['video_or_banner'] == 1){
            if(empty($data['video_url'])){
                return json(['status' => 0, 'msg' =>"请上传视频路径"]);
            }
            $save['video_url'] = $data['video_url'];
        }else{
            if(empty($data['banner_list'])){
                return json(['status' => 0, 'msg' =>"请上传轮播图片路径"]);
            }
        }


        if(!empty($data['type_child_id'])){
            $save['type_child_id'] = $data['type_child_id'];
        }else{
            $save['type_child_id'] = null;
        }

        if(!empty($data['virtual_number'])){
            $save['virtual_number'] = $data['virtual_number'];
            $save['sum_number'] = $data['virtual_number'] + $list['real_number'];
        }

        if(!empty($data['sort'])){
            $save['sort'] = $data['sort'];
        }

        if(!empty($data['status'])){
            $save['status'] = $data['status'];
        }



        $save['content'] = str_replace($domain."/api_project","api_project",$list['content']);

        // 开启事务
        Db::startTrans();
        try {

            $res = $this->Product->where(['id'=>$data['id']])->update($save);
            $resBanner = $this->ProductBanner->where(["product_id"=>$data['id']])->delete();
            $addBanner = [];
            if($data['video_or_banner'] == 2){
                foreach($data['banner_list'] as $k=>$v){
                    $addBanner[] = [
                        "product_id"=>$data['id'],
                        "file_url"=>$v,
                        "sort"=>$k+1,
                        "created_at"=>date("Y-m-d H:i:s"),
                        "update_at"=>date("Y-m-d H:i:s"),
                        "deleted_at"=>date("Y-m-d H:i:s"),
                    ];
                }

                $resBanner = $this->ProductBanner->insertAll($addBanner);
            }

            // 提交事务
            Db::commit();
            return json(['status' => 1, 'msg' => '操作成功']);
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['status' => 0, 'msg' =>$e->getMessage()]);
        }
    }

     // 删除商品
     public function  delProject()
     {
         // 判断店铺是否正常
         $is_store = $this->storeIsNormal($this->uid);
 
         if($is_store['code'] == 1){
             return json(['status' => 0, 'msg' =>$is_store['msg']]);
         }
 
         $store_id = $is_store['store_id'];
 
         $data = request()->post();
 
 
         if(empty($data['id'])){
             return json(['status' => 0, 'msg' =>"请上传产品ID"]);
         }
 
         $list = $this->Product->getOne(['id' =>$data['id'],'deleted_at'=>null]);
 
         if(empty($list)){
             return json(['status' => 0, 'msg' =>"请产品不存在"]);
         }
 
 
         // 开启事务
         Db::startTrans();
         try {
 
             $res = $this->Product->where(['id'=>$data['id']])->update(["deleted_at"=>date("Y-m-d H:i:s")]);
 
             // 提交事务
             Db::commit();
             return json(['status' => 1, 'msg' => '操作成功']);
         } catch (Exception $e) {
             // 回滚事务
             Db::rollback();
             return json(['status' => 0, 'msg' =>$e->getMessage()]);
         }
     }

    // 上传商品图片或者视频
    public function addFile()
    {
        $file = request()->file('file');

        if (!$file) {
            return ['status' => 0, 'msg' => '上传失败，图片不存在'];
        }

        // 获取文件原始扩展名
        $extension = $file->extension();

        $hand = new Handle();

        $dirname = "api_project";

        $savename = $hand->qiniuImg("file", $dirname);

        $add['file_name'] = $savename['fileName'];
        $add['upload_type'] = 2;
        $add['file_path'] = $savename['url'];
        $add['file_type'] = $extension;
        $add['ip'] = Request::ip();
        $add['add_time'] = time();
        $add['user_id'] = $this->uid;
        
        $res = $this->FileLog->create($add);
        $fileLogId = $res->id;
        $savename['file_id'] = $fileLogId;

        return  json($savename);
    }


    // 删除文件
    public function delFile()
    {
        $data = request()->post();

        // 存储空间对应的域名
        $domain = config('sysconfig.qiniu_domain');

        if(empty($data['url'])){
            return json(['status' => 0, 'msg' =>"请上传要删除文件的url"]);
        }


        // 要去掉的子串
        // $substring =  $domain.'/';

        // 使用 str_replace() 函数去掉子串
        // $data['url'] = str_replace($substring, '', $data['url']);

        $hand = new Handle();

        $res = $hand->delQIniuImg($data['url']);

        return  json($res);
    }
   
}
